package com.service.totalauth.config;


import com.service.config.annotation.Distinct;
import com.service.config.utils.JsonXMLUtils;
import com.service.config.utils.RedisUtil;
import com.service.totalauth.dto.UserInfoDto;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import static com.service.config.constant.Constant.USERNAME_OR_NOTFOUND;

/**
 * @ClassName: PreHandler
 * @Description: 拦截器
 * @Author guochuang
 * @Date 2021/10/19
 * @Version 1.0
 */
@Slf4j
public class PreHandler implements HandlerInterceptor {
    private static final Logger LOG = LoggerFactory.getLogger(PreHandler.class);
    private
    @Autowired
    RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否存在注解
        if (!(handler instanceof HandlerMethod)) {
            LOG.info("不是HandlerMethod类型，则无需检查");
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        boolean flag = method.getMethod().isAnnotationPresent(Distinct.class);
        if (!flag) {
            //不存在Distinct注解，则直接通过
            LOG.info("不存在Distinct注解，则直接通过");
            return true;
        }
        RequestWrapperAuthorization requestWrapper = new RequestWrapperAuthorization(request);
        String body =requestWrapper.getBody() ;
        UserInfoDto requestBodEntity = JsonXMLUtils.json2obj(body,UserInfoDto.class);
        if (requestBodEntity.getUsername() == null || requestBodEntity.getPassword() == null
                || "".equals(requestBodEntity.getUsername())|| "".equals(requestBodEntity.getPassword()) ) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null ;
            Map map = new HashMap();
            map.put("code",USERNAME_OR_NOTFOUND);
            map.put("msg","用户名或密码为空,请重新输入");
            out = response.getWriter();
            out.append(JsonXMLUtils.obj2json(map));
            return false;
        }else {
            if (redisUtil.exists(requestBodEntity.getUsername()+requestBodEntity.getPassword())){
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = null ;
                Map map = new HashMap();
                map.put("code",403);
                map.put("msg","该用户的上次请求还未处理完成");
                out = response.getWriter();
                out.append(JsonXMLUtils.obj2json(map));
                return false;
            }else {
                redisUtil.set(requestBodEntity.getUsername()+requestBodEntity.getPassword(),2,JsonXMLUtils.obj2json(body),10);
                return true;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { }
}
